package com.xs.ai.services;

import com.xs.ai.entity.*;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class DailyBriefingService {
    
    private final ChatClient chatClient;
    private final EmailRepository emailRepository;
    private final CalendarEventRepository calendarRepository;
    private final TaskRepository taskRepository;
    
    /**
     * 生成每日简报
     */
    @Scheduled(cron = "0 0 7 * * *") // 每天早上7点
    public void generateDailyBriefings() {
        List<User> activeUsers = userRepository.findAllActive();
        
        for (User user : activeUsers) {
            try {
                generateBriefingForUser(user);
            } catch (Exception e) {
                log.error("生成简报失败: userId={}", user.getId(), e);
            }
        }
    }
    
    private void generateBriefingForUser(User user) {
        LocalDate today = LocalDate.now();
        
        // 1. 收集数据
        List<Email> unreadEmails = emailRepository
            .findUnreadByUser(user.getId(), 100);
        
        List<Email> topPriorityEmails = unreadEmails.stream()
            .filter(e -> "URGENT_CRITICAL".equals(e.getAiPriority()) || 
                        "HIGH_IMPORTANCE".equals(e.getAiPriority()))
            .sorted(Comparator.comparing(Email::getReceivedAt).reversed())
            .limit(10)
            .collect(Collectors.toList());
        
        List<CalendarEvent> todayMeetings = calendarRepository
            .findByUserAndDate(user.getId(), today);
        
        List<Task> pendingTasks = taskRepository
            .findPendingByUser(user.getId());
        
        // 2. 使用AI生成简报
        String briefingContent = generateBriefingWithAI(
            user, topPriorityEmails, todayMeetings, pendingTasks);
        
        // 3. 保存简报
        DailyBriefing briefing = new DailyBriefing();
        briefing.setUserId(user.getId());
        briefing.setBriefingDate(today);
        briefing.setTopEmailsSummary(summarizeEmails(topPriorityEmails));
        briefing.setMeetingsSummary(summarizeMeetings(todayMeetings));
        briefing.setPendingDecisions(extractDecisions(pendingTasks));
        briefing.setAiRecommendations(extractRecommendations(briefingContent));
        
        dailyBriefingRepository.save(briefing);
        
        // 4. 推送简报给用户
        notificationService.sendDailyBriefing(user, briefing);
    }
    
    private String generateBriefingWithAI(User user, 
                                         List<Email> emails,
                                         List<CalendarEvent> meetings,
                                         List<Task> tasks) {
        String prompt = String.format("""
            你是CEO的执行助理。请生成今日工作简报。
            
            ## 数据汇总
            
            ### 待处理重要邮件 (%d封)
            %s
            
            ### 今日会议安排 (%d个)
            %s
            
            ### 待决策事项 (%d项)
            %s
            
            ## 简报要求
            请生成简洁专业的每日简报，以JSON格式返回:
            
            {
              "executiveSummary": "3-4句话的执行摘要，突出最重要的事项",
              "topPriorities": [
                {
                  "item": "优先事项描述",
                  "type": "email | meeting | decision",
                  "urgency": "high | medium",
                  "estimatedTime": "预计处理时间",
                  "quickAction": "一句话的快速行动建议"
                }
              ],
              "emailHighlights": [
                {
                  "from": "发件人",
                  "subject": "主题",
                  "oneLiner": "一句话概括内容",
                  "suggestedAction": "建议操作"
                }
              ],
              "meetingPreview": [
                {
                  "time": "时间",
                  "title": "会议标题",
                  "keyAttendees": ["关键参会人"],
                  "mustKnow": "必须了解的背景信息",
                  "suggestedOutcome": "建议的会议成果"
                }
              ],
              "timeManagementInsights": {
                "totalMeetingHours": 会议总时长,
                "focusTimeAvailable": 可用专注时间,
                "overloadWarning": "如果工作量过大的警告",
                "optimization": "时间优化建议"
              },
              "aiRecommendations": [
                "AI建议1: 具体可执行的建议",
                "AI建议2: ...",
                "AI建议3: ..."
              ]
            }
            
            注意:
            1. 简报要简洁有力，CEO应该在5分钟内读完
            2. 突出需要立即关注的事项
            3. 提供可执行的建议，不要泛泛而谈
            4. 如果发现工作量过大，主动提示
            """,
            emails.size(),
            formatEmailsForPrompt(emails),
            meetings.size(),
            formatMeetingsForPrompt(meetings),
            tasks.size(),
            formatTasksForPrompt(tasks)
        );
        
        return chatClient.call(new Prompt(new UserMessage(prompt)));
    }
}